package com.tdy.servlet;

import com.tdy.application.JerseyApplication;
import com.tdy.filter.StaticsFilter;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.servlet.ServletContainer;
import org.glassfish.jersey.servlet.ServletProperties;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by tangdaoyuan on 15/11/26.
 */
public class BootStrap {
    public static void main(String[] args) {
        try {
//            URI baseUri = UriBuilder.fromUri("http://localhost/").port(9998).build();
            ResourceConfig config = ResourceConfig.forApplication(new JerseyApplication());
//            Server server = JettyHttpContainerFactory.createServer(baseUri);
            Server server = new Server(8080);
            ServletContextHandler handler = new ServletContextHandler(server, "/", ServletContextHandler.SESSIONS);

            //static resources filter
            Map<String, Object> appParams = new HashMap<String, Object>();
            appParams.put(ServletProperties.FILTER_STATIC_CONTENT_REGEX, "(/(statics|lib|lang|css|bower_components|fonts|images|scripts|styles|views|version.*)/.*)|(\\w*\\.\\w+)");

            config.addProperties(appParams);
            ServletContainer container = new ServletContainer(config);

            //context path
            URL url = Thread.currentThread().getContextClassLoader().getResource(".");
            String classes = url.getFile();
            File targetClassesFolder = new File(classes);
            String parantPath = targetClassesFolder.getParentFile().getParent();

            handler.setResourceBase(parantPath);
            handler.addFilter(new FilterHolder(container), "/*", null);
            handler.addFilter(StaticsFilter.class, "/*", null);
            handler.addServlet(DefaultServlet.class, "/");
            handler.setContextPath("/");

            server.setHandler(handler);
            server.start();
            server.join();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.print("jetty start fail");
        }

    }
}
